﻿using ConfExpert.Datasets;
using ConfExpert.Forms.Base;
using ConfExpert.Forms.Kalite;
using ConfExpert.Forms.Siparisler;
using ConfExpert.Properties;
using ConfExpert.Utility;
using DevExpress.Utils;
using DevExpress.XtraEditors;
using DevExpress.XtraEditors.Controls;
using DevExpress.XtraEditors.Repository;
using DevExpress.XtraGrid.Columns;
using DevExpress.XtraGrid.Views.Grid;
using DevExpress.XtraPivotGrid;
using DevExpress.XtraVerticalGrid;
using DevExpress.XtraVerticalGrid.Rows;
using DevTeam;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Windows.Forms;

namespace ConfExpert.Forms.Depo
{
    public partial class DepoStok : XForm
    {
        RepositoryItemComboBox riAtilFaal
        {
            get
            {
                RepositoryItemComboBox ri = new RepositoryItemComboBox();
                ri.TextEditStyle = TextEditStyles.DisableTextEditor;
                ri.Items.AddRange(new object[] { "Atıl", "Faal", "Tümü" });
                return ri;
            }
        }


        //TODO: Tela'da neler çıkmalı? üstteki kombonun, soldaki filter panelin durumu?

        public DepoStok()
        {
            InitializeComponent();
        }

        string stokTuru;
        public DepoStok(string stokTuru)
            : this()
        {
            this.stokTuru = stokTuru;
        }


        List<int> ArticleList;
        public DepoStok(List<int> lst)
            : this("K")
        {
            ArticleList = new List<int>(lst);
        }

        int CikisPartisiId;
        public DepoStok(int cikisPartisiId)
            : this("K")
        {
            CikisPartisiId = cikisPartisiId;
        }

        public string sel
        {
            get
            {
                if (stokTuru == "T")
                    return "Tela";
                else
                    return cmbTip.EditValue.ToString();
            }

            set
            {
                cmbTip.EditValue = value;
            }
        }

        GridManager gm;
        BindingSource bs1, bs2, bsDu4;

        #region Load

        private void DepoStok_Load(object sender, EventArgs e)
        {
            //Register(dockPanel1);
            Session.InvalidateStoklar = false;
            chkRotate.CheckedChanged += chkRotate_CheckedChanged;
            if (stokTuru == "K")
            {
                ds.xStk.Columns.Add("QtyOrdered", typeof(decimal));
                //ds.xStk.Columns.Add("OngETA", typeof(DateTime));
                ds.xStk.Columns.Add("QtyBlocked", typeof(decimal), "SUM(Child(FK_xDU4ihtiyac_xStk_ProductId).BlockedQty)");
                ds.xStk.Columns.Add("QtyNet", typeof(decimal), "ISNULL(Qty,0)-ISNULL(QtyBlocked,0)");
                ds.xStkLines.Columns.Add("CekmeEn", typeof(string));
                ds.xStkLines.Columns.Add("CekmeBoy", typeof(string));
                ds.xStkLines.Columns.Add("TestNotu", typeof(string));
            }
            else
            {
                ds.xStk.Columns.Add("Aciklama", typeof(string));
                ds.xStk.Columns.Add("GrM2", typeof(int));
                ds.xStk.Columns.Add("TelaEn", typeof(int));
                ds.xStk.Columns.Add("Finish", typeof(string));
                ds.xStk.Columns.Add("Cins", typeof(string));
                ds.xStk.Columns.Add("Vendor", typeof(string));
            }

            ds.xStkLines.Columns.Add("Alt", typeof(int), "Iif(ISNULL(OrgId,0)=0 AND ISNULL(AltId,0)=0, 0, 1)");
            ds.xStkLines.Columns.Add("KompozisyonId", typeof(int));
            ds.xStkLines.Columns.Add("Konstruksiyon", typeof(string));
            ds.xStkLines.Columns.Add("FinishId", typeof(int));
            ds.xStkLines.Columns.Add("isAtil", typeof(bool));

            ds.xStk.Columns.Add("Alt", typeof(int), "MAX(Child(FK_xStkLines_xStk_ProductId).Alt)");
            ds.xStk.Columns.Add("TopAdedi", typeof(int), "COUNT(Child(FK_xStkLines_xStk_ProductId).RollId)");
            ds.xStk.Columns["QtySepet"].Expression = "SUM(Child(FK_xStkLines_xStk_ProductId).QtySelected)";
            ds.xStk.Columns.Add("Fark", typeof(decimal), "ISNULL(QtySepet,0)-ISNULL(QtyRequested,0)");

            bs1 = new BindingSource(ds, "xStk");
            bs2 = new BindingSource(bs1, "FK_xStkLines_xStk_ProductId");
            bsDu4 = new BindingSource(bs1, "FK_xDU4ihtiyac_xStk_ProductId");

            //ds.V_Hareketler.ParentRelations.Add("FK_V_Hareketler_xStk_ProductId", ds.xStk.ProductIdColumn, ds.V_Hareketler.ProductIdColumn);

            InitGridView(gvArtikel, bs1);
            DrillDownGrid(gvTop, bs2);

            if (gvArtikel.Columns["StokKodu"] != null)
                gvArtikel.MakeColumnInvisible("StokKodu");

            gvArtikel.YanYanaGetir("Fark:KompozisyonId");
            gvArtikel.YanYanaGetirSoluna("QtyRequested", "QtyInTransit", "ETA");
            gvArtikel.OptionsView.EnableAppearanceEvenRow = gvArtikel.OptionsView.EnableAppearanceOddRow = false;

            //gvArtikel.OptionsView.AllowCellMerge = gvArtikel.OptionsView.EnableAppearanceEvenRow = false;

            //gvArtikel.Columns["ETA"].VisibleIndex = gvArtikel.Columns["QtyInTransit"].VisibleIndex + 1;
            gvTop.MakeColumnInvisible("CustomerId", "Alt", "QtySelected", "AltId");
            gvTop.Columns["IDLE"].ColumnEdit = riIDLE;
            gvTop.AddSummary("Qty", "QtySelected");
            InitPivot(pvt, bs2);
            pvt.CustomAppearance += new PivotCustomAppearanceEventHandler(pvt_CustomAppearance);
            pvt.FocusedCellChanged += new EventHandler(pvt_FocusedCellChanged);
            pvt.CellClick += new PivotCellEventHandler(pvt_CellClick);

            splitContainerControl1.AutoSize();
            splitContainerControl2.AutoSize();

            gm = GridManager.GetManager(gvArtikel);
            //gm.GridMenu.AddMenu("StokAlarm listeme Ekle", StokAlarmEkle, Resources._11);
            //gm.GridMenu.AddMenu("StokAlarm listemden Çıkar", StokAlarmCikar, Resources._1);

            if (stokTuru == "K")
            {
                gm.GridMenu.AddMenu("MUADİL kumaşları göster", MuadilGoster);
                gm.GridMenu.AddMenu("Benzer kumaşları göster", FindSimilar, Resources.CustomerReports_Icon);
                if (ytk(100))
                {
                    gm.GridMenu.AddMenu("Benzer kumaşları göster (TEST)", FindSimilar3);
                    //gm.GridMenu.AddMenu("Benzer kumaşları göster (Eski)", FindSimilar2);
                }
            }

            gm.GridMenu.AddMenu("Kartela etiketi bas", PrintNumuneEtiket);
            //gm.GridMenu.AddMenu("TinEye ile eşleştir", TinyEyeEslestir, Resources.Colors_16x16, true);

            GridManager gm2 = GridManager.GetManager(gvTop);
            gm2.GridMenu.AddMenu("Seçili topları sepete ekle", Sec_Top, Resources.Plus_16x16);
            gm2.GridMenu.AddMenu("Seçili topları sepetten çıkar", Birak_Top, Resources.Minus_16x16);
            if (isKD)
                gm2.GridMenu.AddMenu("Seçili topları serbest bırak", SerbestBirak);

            gm2.GridMenu.AddMenu("Top Hareketleri", ViewRollHistory, Resources.history_16);
            gm2.GridMenu.AddMenu("Atıl Bilgisi", AtilDepoBilgisi);

            //if (WhoAmI == 95 || WhoAmI == 17)
            //    gm2.GridMenu.AddMenu("Top bölme talebi oluştur", TopBolmeTalebiOlustur, Resources.Makas_16x16);

            splitContainerControl2.BorderStyle = BorderStyles.Default;
            splitContainerControl2.Text = string.Empty;
            gvArtikel.RowStyle += new RowStyleEventHandler(gvArtikel_RowStyle);
            gvTop.RowStyle += new RowStyleEventHandler(gvTop_RowStyle);

            gvArtikel.RowCellStyle += new RowCellStyleEventHandler(gvTop_RowCellStyle);
            gvTop.RowCellStyle += new RowCellStyleEventHandler(gvTop_RowCellStyle);
            gvTop.OptionsView.EnableAppearanceEvenRow = false;

            bs1.CurrentChanged += new EventHandler(bs1_CurrentChanged);

            gvArtikel.ColumnPanelRowHeight = 32;
            gvArtikel.Appearance.HeaderPanel.TextOptions.WordWrap = WordWrap.Wrap;
            gvArtikel.MakeReadOnly("QtyRequested");
            gvTop.MakeReadOnly("Note");

            gm.GridMenu.AddMenu("Bu artikelin hareketleri", Hareketler, Resources.StokHareketleri16x16);

            ((RepositoryItemComboBox)cmbTip.Edit).TextEditStyle = TextEditStyles.DisableTextEditor;
            cmbTip.EditValueChanged += cmbTip_EditValueChanged;
            chkEslesme.Checked = ytk(180) ? false : true;

            if (stokTuru == "K")
            {
                LoadKumas();
                if (ArticleList != null)
                {
                    string Ps = string.Empty;
                    foreach (int PId in ArticleList)
                    {
                        MyData.V_KumasRow kr = AppSession.Lookups.V_Kumas.FindByProductId(PId);
                        if (kr != null)
                            Ps += kr.Name + "\r\n";
                    }

                    txtRollIds.EditValue = Ps;
                    sel = "Artikeller";
                }
                else if (CikisPartisiId > 0)
                {
                    sel = "CP";
                    BindArtikel();
                }
                else
                    sel = "*Filtre";
            }
            else
                LoadTela();

            btnGuncelle.ItemClick += btnGuncelle_ItemClick;
            txtRollIds.EditValueChanged += new EventHandler(txtRollIds_EditValueChanged);
            this.Activated += new EventHandler(DepoStok_Activated);

            gvTop.FormatAsNumber(1, "Qty", "En");
            //"QtyOrdered", "QtyConfirmed", "OngETA", "QtyInTransit", "ETA", "QtyGelen", "GelisTarihi"

            gvArtikel.FormatAsNumber(1, "Qty", "QtyAyrilan", "QtyInTransit", "QtyRequested", "QtySepet", "Fark");
            gvArtikel.AddSummary("Qty", "QtyAyrilan", "QtyInTransit", "QtyRequested", "QtySepet", "TopAdedi", "Fark");

            if (stokTuru == "K")
            {
                gvArtikel.FormatAsDate("ETA");
                gvArtikel.FormatAsNumber(1, "QtyAx", "QtyGx", "QtyOrdered");
                gvArtikel.AddSummary("QtyAx", "QtyGx", "QtyOrdered");
            }






            if (sel != "CP")
                gvArtikel.MakeColumnInvisible("QtyAx", "QtyGx", "QtyInTransit");

            btnTopBol.ItemClick += btnTopBol_ItemClick;
            btnKaydet.ItemClick += btnKaydet_ItemClick;
            btnGetir.Click += new EventHandler(btnGetir_Click);
            btnTemizle.Click += new EventHandler(btnTemizle_Click);

            CreateVerticalGrid();
            //dockPanel1.FloatForm.MinimumSize = new Size(200, 800);

            chkTalep.CheckedChanged += chkTalep_CheckedChanged;
            chkTalep_CheckedChanged(null, null);
            
        }

        void btnKaydet_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            //string xml = gvTop.SerializeChanges();

            gvTop.EndEditing();
            DataTable dt = new DataTable("Ozet");
            dt.Columns.AddRange(new DataColumn[] {
                new DataColumn("RollId", typeof(int)),
                new DataColumn("Note", typeof(string))
            });

            DataTable dtChanges = ds.xStkLines.GetChanges();
            if (dtChanges != null)
            {
                foreach (MyData.xStkLinesRow r in dtChanges.Rows)
                    dt.Rows.Add(r["RollId"].ToInt(), r["Note"].ToStr());

                string xml = dt.SerializeChanges();
                ExecuteNonQuery("UpdRollNote", xml);
            }
            ds.xStkLines.AcceptChanges();
            gvTop.RefreshData();
            gvTop.BestFitColumns();
        }

        void chkTalep_CheckedChanged(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (chkTalep.Checked)
                gvArtikel.YanYanaGetirSoluna("KompozisyonId", "QtyRequested", "QtySepet", "Fark");
            else
                gvArtikel.MakeColumnInvisible("QtyRequested", "QtySepet", "Fark");
        }

        void chkRotate_CheckedChanged(object sender, EventArgs e)
        {
            splitContainerControl1.Horizontal = !chkRotate.Checked;
            splitContainerControl1.SplitterPosition = (chkRotate.Checked ? splitContainerControl1.Height : splitContainerControl1.Width) / 2;
        }

        void btnGetir_Click(object sender, EventArgs e)
        {
            Rfrsh();
        }

        private void Rfrsh()
        {
            splitContainerControl1.Enabled = true;
            Session.InvalidateStoklar = false;
            Notify(string.Empty);

            vgc.CloseEditor();
            CustomerId = intParse(GetVal("CustomerId"));
            int BrandId = GetVal("BrandId").ToInt();
            RefreshContextMenu();

            ds.xStkLines.Clear();
            ds.xStk.Clear();
            ds.xDU4ihtiyac.Clear();

            if (BrandId == 290 || CustomerId == 175)
            {
                btnTemizle.PerformClick();
                SetVal("CustomerId", 175);
            }

            GetDetails("xStk;xStkLines;xDU4ihtiyac", "GetStoklar9",
                            WhoAmI,
                            intParse(GetVal("CustomerId")),
                            intParse(GetVal("BrandId")),
                            intParse(GetVal("SezonId")),
                            strParse(GetVal("OrderRef")),
                            intParse(GetVal("ProductId")),
                            strParse(GetVal("Product")),
                            intParse(GetVal("VendorId")),
                            strParse(GetVal("UreticiKodu")),
                            strParse(GetVal("MusteriKodu")),
                            strParse(GetVal("Desc7C")),
                            intParse(GetVal("KaliteId")),
                            intParse(GetVal("KompozisyonId")),
                            strParse(GetVal("Konstruksiyon")),
                            intParse(GetVal("FinishId")),
                            strParse(GetVal("EnGrubu")),
                            intParse(GetVal("FabricTypeId")),
                //intParse(GetVal("DesenYonuId")),
                            intParse(GetVal("DesenId")),
                            intParse(GetVal("OrguId")),
                            strParse(GetVal("Note")),
                            intParse(GetVal("RollId")),
                            intParse(GetVal("OwnerId")),
                //strParse(GetVal("GrupAdi")),
                //intParse(GetVal("GrupESPId")),
                            intParse(GetVal("Grup7CId")),
                            intParse(GetVal("GruppoTexId")),
                            intParse(GetVal("StokGrupId")),
                            strParse(GetVal("Kalite2")),
                            intParse(GetVal("ShelfId")),
                            intParse(GetVal("OrgId")),
                            AF(GetVal("AtilFaal")),
                            !chkEslesme.Checked
                            );

            gvArtikel.BestFitColumns();
            gvTop.BestFitColumns();
        }


        int AF(object x)
        {
            int ret = 0;
            switch (x.ToStr())
            {
                case "Atıl": ret = 1; break;
                case "Faal": ret = 2; break;
            }
            return ret;
        }

        object GetVal(string FieldName)
        {
            return vgc.GetCellValue(vgc.Rows[FieldName], vgc.FocusedRecord);
        }

        void SetVal(string FieldName, object val)
        {
            vgc.SetCellValue((BaseRow)vgc.Rows[FieldName], 0, val);
        }

        void btnTemizle_Click(object sender, EventArgs e)
        {
            foreach (BaseRow r in vgc.Rows)
                vgc.SetCellValue(r, 0, null);
        }





        void btnTopBol_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            decimal tolerans = txtTolerans.EditValue.ToDecimal();
            if (tolerans > 0)
            {
                foreach (MyData.xStkRow s in ds.xStk.Select("QtyRequested>0"))
                {
                    decimal QtyRequested = s.QtyRequested, Total = 0.0M;
                    foreach (MyData.xStkLinesRow so in ds.xStkLines.Select("ProductId = " + s.ProductId.ToString() + " AND QtySelected>0", "Qty DESC"))
                    {
                        Total += so.QtySelected;

                        if (Total - QtyRequested > tolerans)
                            so.QtySelected -= (Total - QtyRequested);
                    }
                }
                UpdSepet();
            }
        }

        void DepoStok_Activated(object sender, EventArgs e)
        {
            if (Session.InvalidateStoklar)
            {
                Notify("İçeriğin değişmiş olma ihtimaline karşı grid donduruldu. İşlem yapabilmek için veriyi GÜNCELLEME'niz veya GETİR demeniz yeterli olacaktır.");
                splitContainerControl1.Enabled = false;
            }            
        }

        void txtRollIds_EditValueChanged(object sender, EventArgs e)
        {
            BindArtikel();
        }


        void pvt_CellClick(object sender, PivotCellEventArgs e)
        {
            CellChanged();
        }

        /*
        void bs2_ListChanged(object sender, ListChangedEventArgs e)
        {
            pvt.Cells.FocusedCell = new Point(pvt.Cells.ColumnCount - 1, pvt.Cells.RowCount - 1);


            for (int J = 0; J < pvt.Cells.RowCount; J++)
            {
                for (int K = 0; K < pvt.Cells.ColumnCount; K++)
                {
                    object cellValue = pvt.Cells.GetCellInfo(J, K).Value;

                    //DO SOMETHING;
                }
            }
            //pvt.Cells.MultiSelection.SetSelection(new Point(0,  1));

        }
        */



        private void LoadKumas()
        {
            this.Text = "Kumaş Stoğu" + (CikisPartisiId > 0 ? " - CPId:" + CikisPartisiId : string.Empty);

            gvTop.OptionsView.ShowFilterPanelMode = DevExpress.XtraGrid.Views.Base.ShowFilterPanelMode.Never;
            btnFiltre.ItemClick += btnFiltre_ItemClick;

            gm.GridMenu.AddMenu("Bu artikelin beklenen gelişleri", BeklenenGelisler, Resources.Saat_16x16);

            btnUygunTop.ItemClick += btnUygunTop_ItemClick;

            gvArtikel.SetCaptions("Qty:IDLE\nMetraj", "QtyAyrilan:Ayrılan\nMetraj", "QtyOrdered:Sip.Edilen\nMetraj", "QtyInTransit:Yüklenen\nMetraj", "QtyRequested:Talep Edilen\nMetraj", "QtySepet:Sepetteki\nMetraj", "KompozisyonId:Kompozisyon", "Notes:Notlar", "ETA:ETA");
            gvTop.SetCaptions("RollId:Top No", "Qty:Topun Metrajı", "OrderRef:Order Ref.", "UreticiKodu:Üretici Kodu", "MusteriKodu:Müşteri Kodu", "Note:Not", "QtySelected:Seçilen Metraj", "LotNr:Lot No");
            gvArtikel.MakeColumnInvisible("GrupESPId", "DesenYonuId", "YTalimatId", "QtyRsvd");

            gvTop.Columns["En"].VisibleIndex = 2;
            gvTop.Columns["En"].Caption = "Kull. En";

            gvArtikel.ShowProductIdAsKumas();
        }

        private void LoadTela()
        {
            btnFiltre.Visibility = btnUygunTop.Visibility = txtTolerans.Visibility = btnTopBol.Visibility = cmbTip.Visibility = DevExpress.XtraBars.BarItemVisibility.Never;
            dockManager.Panels[0].Visibility = DevExpress.XtraBars.Docking.DockVisibility.Hidden;
            //sccAna.PanelVisibility = SplitPanelVisibility.Panel2;

            this.Text = "Tela Stoğu";

            gvArtikel.MakeColumnInvisible("GrupESPId", "DescK", "FabricTypeId", "DesenYonuId", "YTalimatId",
                "Konstruksiyon", "KompozisyonId", "Notes", "MusteriKodu", "QtyInTransit", "Grup7CId", "Desc7C");
            gvTop.MakeColumnInvisible("SezonId", "En", "VendorId", "UreticiKodu", "MusteriKodu", "OwnerId", "QtySelected", "Alt", "KaliteKontrolId", "LotNr");

            BindArtikel();

            gvArtikel.SetCaptions("Aciklama:Açıklama", "TelaEn:En", "Vendor:Üretici", "GrM2:gr/m²", "Qty:IDLE\nMetraj", "QtyAyrilan:Ayrılan\nMetraj", "QtyInTransit:Gelecek\nMetraj", "QtyRequested:Talep Edilen\nMetraj", "QtySepet:Sepetteki\nMetraj", "KompozisyonId:Kompozisyon", "Notes:Notlar", "ETA:ETA");
            gvTop.SetCaptions("RollId:Top No", "Qty:Topun Metrajı", "OrderRef:Order Ref.", "UreticiKodu:Üretici Kodu", "MusteriKodu:Müşteri Kodu", "Note:Not", "QtySelected:Seçilen Metraj", "LotNr:Lot No");

            gvArtikel.Columns["TelaEn"].VisibleIndex = 2;

            gleCust.Visibility = DevExpress.XtraBars.BarItemVisibility.Always;
            txtRollIds.Visibility =
            cmbTip.Visibility = DevExpress.XtraBars.BarItemVisibility.Never;

            //btnSil.Location = new Point(cmbTip.Location.X + 192, btnSil.Location.Y);
            ((RepositoryItemGridLookUpEdit)gleCust.Edit).TextEditStyle = TextEditStyles.DisableTextEditor;
            gleCust.EditValueChanged += gleCust_EditValueChanged;
            gleCust.Edit.Assign(RI(Rp.V_Customer));
            //btnSil.Click += btnSil_Click;


            gvArtikel.ShowProductIdAsTela();
            gvArtikel.BestFitColumns();
        }

        void btnSil_Click(object sender, EventArgs e)
        {
            gleCust.EditValue = null;
        }

        void gleCust_EditValueChanged(object sender, EventArgs e)
        {
            BindArtikel();
        }

        void cmbTip_EditValueChanged(object sender, EventArgs e)
        {
            if (ArticleList != null)
                ArticleList = null;
            else
                txtRollIds.EditValue = null;

            BindArtikel();
        }

        string cpOrderRef;
        public string OrderRef
        {
            get
            {
                if (cpOrderRef != null)
                    return cpOrderRef;
                else
                    return strParse(GetVal("OrderRef"));
            }
        }

        private void RefreshContextMenu()
        {
            gm.GridMenu.RemoveMenu("Seçili artikellerin IDLE toplarını sepete ekle");
            gm.GridMenu.RemoveMenu("Seçili artikellerin tüm toplarını sepetten çıkar");
            gm.GridMenu.RemoveMenu("Seçili artikellerin bu Order Ref.'e ait toplarını sepete ekle");
            gm.GridMenu.RemoveMenu("Seçili artikellerin bu Order Ref.'e ait tüm toplarını sepetten çıkar");

            //TODO: vgc disabled ise bunları yapma!
            if (OrderRef != string.Empty)
            {
                splitContainerControl2.PanelVisibility = SplitPanelVisibility.Panel2;

                //Belli Order Ref.
                gm.GridMenu.AddMenu("Seçili artikellerin bu Order Ref.'e ait toplarını sepete ekle", Sec_Artikel, Resources.Plus_16x16, true);
                gm.GridMenu.AddMenu("Seçili artikellerin bu Order Ref.'e ait tüm toplarını sepetten çıkar", Birak_Artikel, Resources.Minus_16x16);
                AddTooltip(gvArtikel, "QtySepet", "Sepetteki seçili ORDER REF.'E AİT toplam miktarı gösterir.");
            }
            else
            {
                splitContainerControl2.PanelVisibility = SplitPanelVisibility.Both;

                AddTooltip(gvArtikel, "QtySepet", "Sepetteki toplam miktarı gösterir.");


                if (CustomerId == 0)
                {
                    //Tüm Müşteriler            
                }
                else
                {
                    //Belli Müşteri + ESP
                    gm.GridMenu.AddMenu("Seçili artikellerin IDLE toplarını sepete ekle", Sec_Artikel, Resources.Plus_16x16, true);
                    gm.GridMenu.AddMenu("Seçili artikellerin tüm toplarını sepetten çıkar", Birak_Artikel, Resources.Minus_16x16);

                    int t = bs1.Count;
                }

                switch (sel)
                {
                    case "Toplar": // Belli bir top
                    case "Artikeller": // Belli artikeller
                    case "StokAlarm": // StokAlarm listem
                    case "CP": // Çıkış Partisi
                        AddTooltip(gvArtikel, "QtySepet", "Sepetteki toplam miktarı gösterir.");
                        break;
                }
            }
        }
        #endregion

        private void bs1_CurrentChanged(object sender, EventArgs e)
        {
            gcTop.DataSource = bs2;

            int ProductId = intParse(bs1, "ProductId");
            if (ProductId > 0)
            {
                MyData.V_KumasRow kr = AppSession.Lookups.V_Kumas.FindByProductId(ProductId);
                if (kr != null)
                {
                    splitContainerControl2.Text = kr.Name + " artikelinin " +
                    (OrderRef != string.Empty ? OrderRef + " Order Ref.'indeki" : "TÜM depolardaki") + " stok durumu";
                }

                //pvt.DataSource = null;
                pvt.DataSource = bs2;
            }
        }

        private void PrintNumuneEtiket(object sender, EventArgs e)
        {
            string productIds = GetProductIds();
            using (KartelaEtiketi ke = new KartelaEtiketi(CustomerId, productIds))
                ke.ShowDialog();
        }

        private string GetProductIds()
        {
            string ids = "";
            foreach (int rowHandle in gvArtikel.GetSelectedRows())
            {
                if (rowHandle > -1)
                {
                    string pId = gvArtikel.GetRowCellValue(rowHandle, "ProductId").ToString();

                    if (pId != "")
                        ids += pId + ",";
                }
            }

            ids = ids.RemoveIfEndsWith(",");

            return ids;
        }

        void btnGuncelle_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (sel == "*Filtre")
                Rfrsh();
            else
                BindArtikel();

            Notify("Stok Durumu güncellendi.");
        }

        private void UpdSepet()
        {
            DataTable dt = new DataTable("Ozet");
            dt.Columns.AddRange(new DataColumn[] {
                new DataColumn("RollId", typeof(int)),
                new DataColumn("QtySelected", typeof(decimal))
            });

            DataTable dtChanges = ds.xStkLines.GetChanges();
            if (dtChanges != null)
            {
                foreach (MyData.xStkLinesRow r in dtChanges.Rows)
                    dt.Rows.Add(r.RollId, r.QtySelected);

                ExecuteNonQuery("UpdSepet2", WhoAmI, dt.SerializeChanges());
            }
            ds.xStkLines.AcceptChanges();
            gvTop.RefreshData();
        }

        private void SepetiTemizle()
        {
            ExecuteNonQuery("SepetiBosalt", WhoAmI);

            foreach (MyData.xStkLinesRow r in ds.xStkLines)
                if (!r.IsQtySelectedNull())
                    r.SetQtySelectedNull();
        }

        private void Hareketler(object sender, EventArgs e)
        {
            int productId = bs1.GetCurrentValue("ProductId").ToInt(-1);
            if (productId > 0)
                using (DepoStokHareketler rzv = new DepoStokHareketler(productId))
                {
                    rzv.ShowDialog();
                }
        }

        private void BeklenenGelisler(object sender, EventArgs e)
        {
            int pid = intParse(bs1, "ProductId");
            if (pid > 0)
                using (InTransit it = new InTransit(pid))
                {
                    it.Text = "Beklenen Gelişler";
                    it.ShowDialog();
                }
            //else
            //    if (strParse(bs1, "StokKodu") != string.Empty)
            //        using (InTransit it = new InTransit(strParse(bs1, "StokKodu")))
            //        {
            //            it.Text = "Beklenen Gelişler";
            //            it.ShowDialog();
            //        }

        }

        private void gleCustomer_Closed(object sender, ClosedEventArgs e)
        {
            vgc.CloseEditor();
            if (intParse(GetVal("CustomerId")) > 0)
                Rfrsh();
        }

        private void PrepareImageComboBoxEdit(string colName, string opts)
        {
            RepositoryItemImageComboBox imageCombo = gvTop.GridControl.RepositoryItems.Add("ImageComboBoxEdit") as RepositoryItemImageComboBox;
            imageCombo.Items.BeginUpdate();
            int ndx = 0;
            imageCombo.SmallImages = ErrorOk;

            foreach (string opt in opts.Split('|'))
                imageCombo.Items.Add(new ImageComboBoxItem(opt, ndx++));
            imageCombo.GlyphAlignment = DevExpress.Utils.HorzAlignment.Center;
            imageCombo.Items.EndUpdate();
            gvTop.Columns[colName].ColumnEdit = imageCombo;
        }

        /*
        private void RengeGoreSirala(object sender, EventArgs e)
        {
            gvArtikel.SortInfo.ClearAndAddRange(new GridColumnSortInfo[] { new GridColumnSortInfo(gvArtikel.Columns["Hue"], ColumnSortOrder.Ascending) });
            gvArtikel.RefreshData();
        }
*/

        private void BindArtikel()
        {
            splitContainerControl1.Enabled = true;
            Session.InvalidateStoklar = false;
            Notify(string.Empty);

            cmbTip.Visibility = (sel != "CP" && sel != "Tela") ? DevExpress.XtraBars.BarItemVisibility.Always : DevExpress.XtraBars.BarItemVisibility.Never;
            txtRollIds.Visibility = (sel == "Toplar" || sel == "Artikeller" || sel == "Raflar") ? DevExpress.XtraBars.BarItemVisibility.Always : DevExpress.XtraBars.BarItemVisibility.Never;
            //sccAna.PanelVisibility = sel == "*Filtre" ? SplitPanelVisibility.Both : SplitPanelVisibility.Panel2;

            if (sel != "*Filtre")
            {
                btnTemizle.PerformClick();

                ds.xStk.Clear();
                ds.xStkLines.Clear();
                ds.xDU4ihtiyac.Clear();

                btnUygunTop.Enabled = CustomerId > 0;

                //TODO: TelaVendor-Cins-Finish gözüküyor mu??
                string flt = txtRollIds.EditValue.ToStr().Trim().Replace("\r\n", ",");
                if ((sel == "Raflar" || sel == "Artikeller" || sel == "Toplar") &&
                    flt == string.Empty)
                    flt = "!";

                switch (sel)
                {
                    case "Tela":
                        flt = intParse(gleCust.EditValue).ToString();
                        CustomerId = intParse(gleCust.EditValue);
                        gvArtikel.MakeColumnInvisible("ETA", "QtyRsvd", "StokGrupId", "KVendorId", "KCustomerId", "KaliteId", "FinishId", "DesenId", "OrguId", "Agirlik", "RaporBoyuId", "EspId", "EspQty", "Alt");
                        break;

                    case "CP":
                        flt = CikisPartisiId.ToString();
                        break;
                }

                GetDetails("xStk;xStkLines;xBuffer", "GetStoklar2", sel, flt, WhoAmI);

                if (ds.xBuffer.Rows.Count > 0)
                {
                    cpOrderRef = ds.xBuffer[0]["strVal"].ToString();
                    CustomerId = intParse(ds.xBuffer[0].intVal);
                    //gvArtikel.SelectAll();

                    if (!Session.InvalidateStoklar)
                    {
                        gvArtikel.MoveLast();
                        int son = gvArtikel.FocusedRowHandle;
                        gvArtikel.MoveFirst();
                        gvArtikel.SelectCells(0, gvArtikel.Columns["QtyRequested"], son, gvArtikel.Columns["QtyRequested"]);

                        btnUygunTop.Enabled = true;
                        btnUygunTop.PerformClick();
                        gvArtikel.UnSelectCells(1, gvArtikel.Columns["QtyRequested"], son, gvArtikel.Columns["QtyRequested"]);
                    }
                }

                gvArtikel.BestFitColumns();
                gvArtikel.Columns["MusteriKodu"].Width = 90;
                gvTop.BestFitColumns();
            }

            RefreshContextMenu();
        }

        #region Yakın Renkler

        void FindSimilar(object sender, EventArgs e)
        {
            int productID = bs1.GetCurrentValue("ProductId").ToInt(-1);
            FindSimilarBenzerRenk(productID, 1);
        }

        void FindSimilar2(object sender, EventArgs e)
        {
            int productID = bs1.GetCurrentValue("ProductId").ToInt(-1);
            FindSimilarBenzerRenk(productID, 2);
        }

        void FindSimilar3(object sender, EventArgs e)
        {
            int productID = bs1.GetCurrentValue("ProductId").ToInt(-1);
            FindSimilarBenzerRenk(productID, 3);
        }

        void MuadilGoster(object sender, EventArgs e)
        {
            int productId = bs1.GetCurrentValue("ProductId").ToInt(-1);
            if (productId > 0)
                using (Equiv eq = new Equiv(productId))
                    eq.ShowDialog();
        }

        void StokAlarmEkle(object sender, EventArgs e)
        {
            string lst = string.Empty;
            if (gvArtikel.GetSelectedRows().Length > 0)
                foreach (int handle in gvArtikel.GetSelectedRows())
                    lst += intParse(gvArtikel.GetRowCellValue(handle, "ProductId")) + ",";

            ExecuteNonQuery("UpdStokAlarmEkleCikar", WhoAmI, lst + "0", 'E');
        }

        void StokAlarmCikar(object sender, EventArgs e)
        {
            string lst = string.Empty;
            if (gvArtikel.GetSelectedRows().Length > 0)
                foreach (int handle in gvArtikel.GetSelectedRows())
                    lst += intParse(gvArtikel.GetRowCellValue(handle, "ProductId")) + ",";

            ExecuteNonQuery("UpdStokAlarmEkleCikar", WhoAmI, lst + "0", 'Ç');

            if (sel == "StokAlarm")
                btnGuncelle.PerformClick();
        }

        #endregion
        void btnFiltre_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        //private void btnAra_Click(object sender, EventArgs e)
        {
            using (FuzzySearch fuzzy = new FuzzySearch(true))
            {
                if (fuzzy.ShowDialog() == DialogResult.OK)
                {
                    //TODO KG: OPS.. locatebyvalue invisible sütunda işe yarıyor mu kontrol etmek lazım
                    gvArtikel.FocusedRowHandle = gvArtikel.LocateByValue("ProductId", fuzzy.ProductId);
                    gvArtikel.MakeRowVisible(gvArtikel.FocusedRowHandle);
                    //rengini yeşil yap!
                }
            }
            ActivateFilter();
        }

        private PivotGridField AddNewField(PivotGridControl pgc, string FieldName, string Caption, PivotArea pa)
        {
            PivotGridField fd = new PivotGridField();
            fd.FieldName = FieldName;
            fd.CellFormat.FormatType = DevExpress.Utils.FormatType.Numeric;
            fd.CellFormat.FormatString = "#,###.##";
            fd.SetAreaPosition(pa, 0);
            pgc.Fields.Add(fd);
            fd.Name = "_" + FieldName;
            fd.Caption = Caption;
            return fd;
        }

        private void InitPivot(PivotGridControl pgc, BindingSource bs)
        {
            //pvt.FieldValueImageIndex += new DevExpress.XtraPivotGrid.PivotFieldImageIndexEventHandler(this.pvt_FieldValueImageIndex);                        
            //pvt.DataSource = bs;
            //pvt.ValueImages = imageList1;
            //pvt.BestFit();

            pgc.DataSource = bs;
            pgc.OptionsCustomization.CustomizationFormStyle = DevExpress.XtraPivotGrid.Customization.CustomizationFormStyle.Excel2007;
            pgc.FieldValueDisplayText += new PivotFieldDisplayTextEventHandler(pivotGrid_FieldValueDisplayText);
            pgc.BeginUpdate();

            PivotGridFieldBase[] pgf2 = new PivotGridFieldBase[3];
            pgf2[0] = AddNewField(pgc, "IDLE", "IDLE", PivotArea.RowArea);
            pgf2[0].Caption = "Durum";
            ((PivotGridField)pgf2[0]).FieldEdit = riIDLE;

            pgf2[1] = AddNewField(pgc, "BrandId", "Marka", PivotArea.RowArea);
            ((PivotGridField)pgf2[1]).FieldEdit = RI(Rp.Brand);

            pgf2[2] = AddNewField(pgc, "OrderRef", "Order Ref.", PivotArea.RowArea);
            pgf2[2].ExpandedInFieldsGroup = false;
            pgc.Groups.Add(pgf2, "IDLEBrand");

            AddNewField(pgc, "SezonId", PivotArea.FilterArea).FieldEdit = RI(Rp.Sezon);
            AddNewField(pgc, "VendorId", PivotArea.FilterArea).FieldEdit = RI(Rp.Vendor);
            AddNewField(pgc, "CustomerId", PivotArea.FilterArea).FieldEdit = RI(Rp.V_Customer);

            AddNewField(pgc, "Qty", "Metraj", PivotArea.DataArea);

            //.Width = 40;  .Visible = true;
            //    fld.SummaryType = DevExpress.Data.PivotGrid.PivotSummaryType.Sum;

            foreach (PivotGridField pgf in pgc.Fields)
            {
                pgf.SortOrder = PivotSortOrder.Ascending;
                pgf.Options.AllowSort = DevExpress.Utils.DefaultBoolean.True;
            }
            pgc.EndUpdate();
        }

        private RepositoryItemGridLookUpEdit riIDLE
        {
            get
            {
                DataTable idle = new DataTable();
                idle.Columns.Add("IDLE", typeof(int));
                idle.Columns.Add("Desc", typeof(string));

                RepositoryItemGridLookUpEdit ri = new RepositoryItemGridLookUpEdit();
                ri.TextEditStyle = TextEditStyles.DisableTextEditor;
                ri.DataSource = idle;
                ri.DisplayMember = "Desc";
                ri.ValueMember = "IDLE";
                ri.View.PopulateColumns();

                int idx = 0;
                foreach (string str in "AYRILMIŞ;REZERVE;IDLE;ÇIKILACAK;ONAY_BEKLEYEN;KALİTE_KONTROL_BEKLEYEN".Split(';'))
                    idle.Rows.Add(idx++, str);

                return ri;
            }
        }

        void btnUygunTop_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (gvArtikel.GetSelectedRows().Length > 0)
            {
                foreach (int handle in gvArtikel.GetSelectedRows())
                {
                    DataRow dr = gvArtikel.GetDataRow(handle);
                    decimal qtyRequested = dr["QtyRequested"].ToDecimal(-1);
                    decimal qtySepet = dr["QtySepet"].ToDecimal(-1);
                    if (qtySepet == 0 && qtyRequested == 0)
                        continue;

                    int ProductId = dr["ProductId"].ToInt(-1);

                    Dictionary<int, decimal> subSet = new Dictionary<int, decimal>();

                    foreach (MyData.xStkLinesRow xr in ds.xStkLines.Select(SelectionCriteria(ProductId), "Qty"))
                    {
                        xr.QtySelected = 0;
                        subSet.Add(xr.RollId, xr.Qty);
                    }

                    List<int> selectedRollIds = SubsetSum.Select(qtyRequested, subSet);

                    foreach (int rollId in selectedRollIds)
                    {
                        MyData.xStkLinesRow drSelectedRoll = ds.xStkLines.FindByRollId(rollId);
                        drSelectedRoll.QtySelected = drSelectedRoll.Qty;
                    }
                }
                UpdSepet();
            }
            //else
            //{
            //    ShowInfoMessage("Lütfen önce ilgili kumaşları seçiniz.");
            //}
        }

        #region Seç & Bırak
        void Sec_Artikel(object sender, EventArgs e)
        {
            foreach (int handle in gvArtikel.GetSelectedRows())
            {
                int ProductId = gvArtikel.GetRowCellValue(handle, "ProductId").ToInt();

                string filter = string.Empty;

                if (stokTuru == "K")
                    filter = SelectionCriteria(ProductId);

                else //if (stokTuru == "T")
                    filter = "Qty>0 AND OrderRef is null AND ProductId = " + ProductId.ToString();

                foreach (MyData.xStkLinesRow r in ds.xStkLines.Select(filter, "Qty"))
                    r.QtySelected = r.Qty;

                //OWNERId leri uygun olmayanları zaten AYRIM'da gösterme!
            }
            UpdSepet();
        }

        string SelectionCriteria(int ProductId)
        {
            return //" (DepoId <> 4" + (AmI(53, 95, 175, 120) ? " OR 1=1" : "") + ") AND " +
                   " (ProductId = " + ProductId.ToString() + " AND IDLE <= 2 AND (" +
                //            return " (ProductId = " + ProductId.ToString() + " AND IDLE <= 2 AND (" +
                    (OrderRef != string.Empty ? "OrderRef = '" + OrderRef + "' OR " : string.Empty) +
                    "OrderRef is null AND (" +
                    (sel == "ESP" ? "CustomerId=175 OR " : string.Empty) +
                    "CustomerId = " + CustomerId.ToString() + ")))";
        }

        void Sec_Top(object sender, EventArgs e)
        {
            bool NA = false;
            foreach (int handle in gvTop.GetSelectedRows())
            {
                int DepoId = gvTop.GetRowCellValue(handle, "DepoId").ToInt();
                if (intParse(gvTop.GetRowCellValue(handle, "IDLE")) <= 2 && ((DepoId != 4 && DepoId != 5) || ytk(104)))
                {
                    int RollId = intParse(gvTop.GetRowCellValue(handle, "RollId"));
                    ds.xStkLines.FindByRollId(RollId).QtySelected = ds.xStkLines.FindByRollId(RollId).Qty;
                }
                else
                    NA = true;
            }
            UpdSepet();

            if (NA)
                XtraMessageBox.Show("Seçtiğiniz toplardan askıda olanlar (ONAY_BEKLEYEN, ÇIKILACAK veya KALİTE_KONTROL_BEKLEYEN) ve DU4/DESTEX rafındakiler sepete atılamaz.");
        }

        void Birak_Artikel(object sender, EventArgs e)
        {
            foreach (int handle in gvArtikel.GetSelectedRows())
            {
                int ProductId = gvArtikel.GetRowCellValue(handle, "ProductId").ToInt();
                foreach (MyData.xStkLinesRow r in ds.xStkLines.Select("ProductId = " + ProductId.ToString()))
                    r.QtySelected = 0;
            }
            UpdSepet();
        }

        void AtilDepoBilgisi(object sender, EventArgs e)
        {
            gvTop.EndEditing();
            string RollIds = gvTop.GetSelectedValues("RollId");
            if (RollIds != string.Empty)
            {
                DataSet dsx = ExecuteDataSet("GetAtilSebep", RollIds);
                if (dsx.Tables[0].Rows.Count > 0)
                    using (AtilSebep sb = new AtilSebep(dsx))
                        sb.ShowDialog();
            }
        }

        void ViewRollHistory(object sender, EventArgs e)
        {
            int RollId = gvTop.GetRowCellValue(gvTop.FocusedRowHandle, "RollId").ToInt();
            using (TopGecmisi tg = new TopGecmisi(RollId))
                tg.ShowDialog();
        }

        void Birak_Top(object sender, EventArgs e)
        {
            foreach (int handle in gvTop.GetSelectedRows())
            {
                int RollId = intParse(gvTop.GetRowCellValue(handle, "RollId"));
                ds.xStkLines.FindByRollId(RollId).QtySelected = 0;
            }
            UpdSepet();
        }

        void SerbestBirak(object sender, EventArgs e)
        {
            gvTop.EndEditing();
            if (gvTop.GetSelectedValues("RollId") != string.Empty)
                using (SerbestBirak sb = new SerbestBirak(gvTop.GetSelectedValues("RollId")))
                    sb.ShowDialog();
        }
        #endregion

        //void TopBolmeTalebiOlustur(object sender, EventArgs e)
        //{
        //    if (gvTop.FocusedRowHandle > -1)
        //    {
        //        int RollId = (int)gvTop.GetFocusedRowCellValue("RollId");

        //        using (TopBolme bol = new TopBolme(RollId, CustomerId, stokTuru))
        //        {
        //            bol.ShowDialog();
        //            if (bol.DialogResult == System.Windows.Forms.DialogResult.OK)
        //            {
        //                ds.Tables["xStkLines"].Merge(bol.xs);
        //            }
        //        }
        //    }
        //}

        #region Style

        void pvt_CustomAppearance(object sender, PivotCustomAppearanceEventArgs e)
        {
            //int brandId = intParse(e.GetFieldValue(pvt.Fields["BrandId"]));
            //if (brandId > 0)
            {
                if (/*CustomerId == -1 && */ e.Focused)
                    e.Appearance.BackColor = e.Appearance.BackColor2 = Color.YellowGreen;   // Color.FromArgb(255, 192, 0);


                /*
            //else if (Equals(e.GetFieldValue(pivot.Fields["CustomerId"]), CustomerId) &&
            else if (AppSession.Lookups.Brand.FindByBrandId(brandId).CustomerId == CustomerId &&
                Equals(e.GetFieldValue(pvt.Fields["IDLE"]), 1))
                e.Appearance.BackColor = e.Appearance.BackColor2 = Color.YellowGreen;
            else if (CustomerId == -175 &&
                brandId == 290 &&
                Equals(e.GetFieldValue(pvt.Fields["IDLE"]), 1))
                e.Appearance.BackColor = e.Appearance.BackColor2 = Color.YellowGreen;
                 */
            }
        }

        void pvt_FocusedCellChanged(object sender, EventArgs e)
        {
            CellChanged();
        }

        bool changing = false;
        private void CellChanged()
        {
            if (!changing)
                try
                {
                    changing = true;
                    if (!gcArtikel.IsDisposed && pvt.Cells.GetFocusedCellInfo() != null)
                        gcTop.DataSource = pvt.Cells.GetFocusedCellInfo().CreateDrillDownDataSource();
                    else
                        gcTop.DataSource = null;

                    pvt.Invalidate();
                    gvTop.BestFitColumns();
                }
                finally
                {
                    changing = false;
                }
        }








        int _CustomerId;
        int CustomerId
        {
            get { return _CustomerId; }
            set
            {
                if (_CustomerId == value) return;
                _CustomerId = value;
            }
        }

        void gvArtikel_RowStyle(object sender, DevExpress.XtraGrid.Views.Grid.RowStyleEventArgs e)
        {
            GridView gv = sender as GridView;

            if (decimalParse(gv.GetRowCellValue(e.RowHandle, "QtySepet")) > 0)
                e.Appearance.BackColor = Color.LightBlue;

            if (intParse(gv.GetRowCellValue(e.RowHandle, "Alt")) > 0)
                e.Appearance.ForeColor = SystemColors.HotTrack;

            //else
            //    e.Appearance.Combine((e.RowHandle & 1) != 0 ? ((GridView)sender).Appearance.EvenRow : ((GridView)sender).Appearance.OddRow);

            //e.Appearance.BackColor = ((GridView)sender).GetRowCellDisplayText(e.RowHandle, "QtySepet").ToString() != string.Empty ? Color.LightBlue : Color.White;
        }

        void gvTop_RowCellStyle(object sender, RowCellStyleEventArgs e)
        {
            if (e.RowHandle > -1)
                if (e.Column.FieldName == "Qty")
                    e.Appearance.Font = new Font(AppearanceObject.DefaultFont, FontStyle.Bold);
        }

        void gvTop_RowStyle(object sender, DevExpress.XtraGrid.Views.Grid.RowStyleEventArgs e)
        {
            GridView gv = sender as GridView;

            if (decimalParse(gv.GetRowCellValue(e.RowHandle, "QtySelected")) > 0)
                e.Appearance.BackColor = Color.LightBlue;

            if (intParse(gv.GetRowCellValue(e.RowHandle, "Alt")) > 0)
                e.Appearance.ForeColor = SystemColors.HotTrack;
            else
                if (boolParse(gv.GetRowCellValue(e.RowHandle, "isAtil")))
                    e.Appearance.ForeColor = Color.Purple;

            //else
            //    e.Appearance.Combine((e.RowHandle & 1) != 0 ? ((GridView)sender).Appearance.EvenRow : ((GridView)sender).Appearance.OddRow);

            //e.Appearance.BackColor = ((GridView)sender).GetRowCellDisplayText(e.RowHandle, "QtySelected").ToString() != string.Empty ? Color.LightBlue : Color.White;
        }
        #endregion

        private void ActivateFilter()
        {
            if (AppSession.SonArama != null && AppSession.SonArama != string.Empty)
            {
                bs1.Filter = "ISNULL(ProductId,0) in (" + AppSession.SonArama + ",-1)";

                List<int> vr = new List<int>();
                int dataRowCount = gvArtikel.DataRowCount;
                // Traverse data rows and change the Price field values. 
                for (int i = 0; i < dataRowCount; i++)
                    vr.Add(gvArtikel.GetRowCellValue(i, "ProductId").ToInt());

                ds.xSonAramaEksik.Clear();
                GetDetails("xSonAramaEksik", "GetSonAramaEksik", AppSession.SonArama, string.Join(",", vr.ToArray()));

                if (ds.xSonAramaEksik.Rows.Count > 0)
                    using (SonAramaEksikler sae = new SonAramaEksikler(ds.xSonAramaEksik))
                    {
                        sae.ShowDialog();
                    }

            }
            else
                bs1.Filter = string.Empty;

            btnFiltre.Caption = "Filtre" + (AppSession.SonArama.ToStr() != string.Empty ? "+" : string.Empty);
        }

        public void AddFilterPanelItem(VGridControl vgv, params string[] pairs)
        {
            foreach (string pair in pairs)
            {
                string[] vals = pair.Split(':');
                string fieldName = vals[0];
                string caption = fieldName;

                if (vals.Length > 1)
                    caption = vals[1];

                EditorRow row = new EditorRow();
                row.Properties.Caption = caption;
                row.Name = fieldName;
                row.Height = 20;

                RepositoryItem ri = GetFieldRI(fieldName);
                bool autoCompleted = (ri == null);

                switch (fieldName)
                {
                    case "RollId":
                    case "AtilFaal":
                        break;

                    default:
                        if (autoCompleted)
                            ri = GetCustomGLE(new DataTable(), fieldName, fieldName);

                        ri.Name = fieldName;
                        row.Properties.RowEdit = (RepositoryItem)ri.Clone();

                        if (row.Properties.RowEdit is RepositoryItemGridLookUpEdit)
                        {
                            RepositoryItemGridLookUpEdit r = (RepositoryItemGridLookUpEdit)row.Properties.RowEdit;
                            r.QueryPopUp -= FilterPanel_PopUp;
                            r.QueryPopUp += FilterPanel_PopUp;
                            if (autoCompleted)
                                r.ProcessNewValue += r_ProcessNewValue;
                        }
                        break;
                }

                vgv.Rows.Add(row);
            }
            //return row;
        }

        void r_ProcessNewValue(object sender, ProcessNewValueEventArgs e)
        {
            string newEntry = e.DisplayValue.ToString();
            if (newEntry != string.Empty)
            {
                ((DataTable)((GridLookUpEdit)sender).Properties.DataSource).Rows.Add(newEntry);
                e.Handled = true;
            }
        }



        public void FilterPanel_PopUp(object sender, CancelEventArgs e)
        {
            GridLookUpEdit gle = sender as GridLookUpEdit;

            string name = gle.Properties.Name;

            string ActiveFilter = string.Empty;
            List<string> filters = new List<string>();
            foreach (EditorRow row in vgc.Rows)
            {

                string val = vgc.GetCellValue(row, 0).ToStr();
                string colName = row.Name;
                if (val != "")
                    if (row.Name != "AtilFaal")
                    {
                        if (colName.ToLower().EndsWith("Id".ToLower()))
                            filters.Add(row.Name + "= " + val);
                        else
                            filters.Add(row.Name + " like '" + val + "'");
                    }
            }

            if (filters.Count > 0)
                ActiveFilter = "(" + string.Join(") AND (", filters.ToArray()) + ")";

            DataTable dtAutoComp = ExecuteDataTable("GetAutoComp", name, ActiveFilter);
            if (dtAutoComp.Rows.Count > 0)
                dtAutoComp = dtAutoComp.Select("", dtAutoComp.Columns[0].ColumnName).CopyToDataTable();

            if (name.ToLower().EndsWith("Id".ToLower()) && name.ToLower() != "RollId".ToLower())
            {
                DataTable dtGle = (DataTable)gle.Properties.DataSource;

                DataTable dtSource = AppSession.Lookups.Tables[dtGle.TableName];
                DataTable dtNew = dtSource.Clone();

                foreach (DataRow dr in dtAutoComp.Rows)
                {
                    int id = (int)dr[0];
                    DataRow foundRow = dtSource.Rows.Find(id);
                    if (foundRow != null)
                        dtNew.ImportRow(foundRow);
                }

                if (dtNew.Rows.Count > 0)
                    dtNew = dtNew.Select("", "Name").CopyToDataTable();

                dtNew.TableName = dtSource.TableName;

                gle.Properties.DataSource = dtNew;

                for (int i = 0; i < dtNew.Columns.Count; i++)
                {
                    string colName = dtNew.Columns[i].ColumnName;
                    GridColumn gc = gle.Properties.View.Columns[colName];
                    if (gc != null && gc.Visible)
                    {
                        gc.VisibleIndex = i;
                    }
                }
            }
            else
            {
                //vgv.Rows[name].Properties.RowEdit = RepositoryManager.GetAutoCompGLE(dtAutoComp,name);
                var ri = vgc.Rows[name].Properties.RowEdit as RepositoryItemGridLookUpEdit;
                ri.DataSource = dtAutoComp;
                ri.DisplayMember = ri.ValueMember = name;
                gle.Properties.DataSource = dtAutoComp;
            }
        }

        public void CreateVerticalGrid()
        {
            AddFilterPanelItem(vgc,
                 "CustomerId:Müşteri"
                , "BrandId:Marka"
                , "SezonId:Sezon"
                , "OrderRef:OrderRef."
                , "ProductId"
                , "Product:Artikel"
                , "VendorId:Üretici"
                , "UreticiKodu:Üretici Kodu"
                , "MusteriKodu:Müşteri Kodu"
                , "Desc7C:7C Açıklama"
                , "DescK:Açıklama"
                , "KaliteId:Kalite"
                , "KompozisyonId:Kompozisyon"
                , "Konstruksiyon"
                , "FinishId:Finish"
                , "EnGrubu:En Grubu"
                , "FabricTypeId:Fabric Type"
                , "DesenId:Desen"
                , "OrguId:Örgü"
                , "RollId:TopId"
                , "OwnerId:Sahibi"
                , "Grup7CId:7C Grup"
                , "GruppoTexId:Gruppo Tex"
                , "StokGrupId:Stok Grup"
                , "ShelfId:Raf"
                , "Note:Notlar"
                , "OrgId:Orjinal ProductId"
                , "AtilFaal:Atıl/Faal"
                );

            vgc.Rows["AtilFaal"].Properties.RowEdit = riAtilFaal;
            vgc.SetCellValue(vgc.Rows["AtilFaal"], 0, "Tümü");

            ////vgc.Rows.GetRowByFieldName("Note", true).Height = 60;
            ////vgc.Rows.GetRowByFieldName("Product", true).Properties.Caption = "STOKKODU";

            //RepositoryItemGridLookUpEdit ri = (RepositoryItemGridLookUpEdit)vgc.Rows.GetRowByFieldName("CustomerId", true).Properties.RowEdit;
            //ri.Closed += new ClosedEventHandler(gleCustomer_Closed);
            //ri.TextEditStyle = TextEditStyles.DisableTextEditor;

            //pvt.Width = 400;
            //dockPanel1.Width = 400;

            vgc.OptionsBehavior.UseEnterAsTab = true;
            vgc.LayoutStyle = DevExpress.XtraVerticalGrid.LayoutViewStyle.SingleRecordView;
            vgc.CustomDrawRowHeaderCell += new DevExpress.XtraVerticalGrid.Events.CustomDrawRowHeaderCellEventHandler(vgc_CustomDrawRowHeaderCell);
            vgc.Appearance.RowHeaderPanel.BackColor = Color.LightBlue;

            vgc.FocusedRow = vgc.Rows["CustomerId"];
            //vgc.SetCellValue(vgc.Rows["CustomerId"], 0, 1);
            vgc.BestFit();
        }



    }
}